package com.tengju.user.application.sign;

import com.tengju.user.application.shared.ApplicationException;
import com.tengju.user.application.shared.ApplicationExceptionCode;
import com.tengju.user.domain.model.archive.letax.LetaxAccount;
import com.tengju.user.domain.model.archive.letax.LetaxStatus;
import com.tengju.user.domain.model.archive.sign.*;
import com.tengju.user.domain.model.sign.License;
import com.tengju.user.domain.model.sign.LicenseType;
import com.tengju.user.domain.model.user.UserIdCode;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class SignService {

    private final SignRepository signRepository;
    private final SelfCertificationRepository selfCertificationRepository;
    private final LetaxRegisteredRepository letaxRegisteredRepository;


    public Map<Integer, License> getLicenses(UserIdCode idCode) {
        Sign sign = signRepository.find(idCode);

        if (sign == null) {
            throw ApplicationException.error(ApplicationExceptionCode.INVALID_DATA,"用户未签约");
        }

        Map<Integer, License> licenses = new HashMap<>();
        if (sign.isSelfCertified()) {
            SelfCertification selfCertification = selfCertificationRepository.findOne(idCode);
            licenses.put(LicenseType.SOCIAL_CREDIT.getVal(), selfCertification.companyLicense());
            licenses.put(LicenseType.IDCARD.getVal(), selfCertification.legalLicense());
        } else if (sign.isRegister()) {
            LetaxAccount letaxAccount = letaxRegisteredRepository.getLetaxAccount(idCode, LetaxStatus.FINISHED);
            licenses.put(LicenseType.IDCARD.getVal(), letaxAccount.license());
        }
        return licenses;
    }


    public SignInfo getSignInfo(UserIdCode idCode) {
        Sign sign = signRepository.find(idCode);
        if (sign == null) {
            return null;
        }
        SelfCertification selfCertification = null;
        LetaxAccount letaxAccount = null;
        if (sign.isSelfCertified()) {
            selfCertification = selfCertificationRepository.findOne(idCode);
        } else if (sign.isRegister()) {
            letaxAccount = letaxRegisteredRepository.getLetaxAccount(idCode, LetaxStatus.FINISHED);
        }
        return new SignInfo(sign.getCurrentIdentity(),
                sign,
                selfCertification,
                letaxAccount);
    }
}
